/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "NumericTextEdit.h"

#include <QtGui/QMouseEvent>
#include  <float.h>

namespace PQBuilder
{
	NumericTextEdit::NumericTextEdit(QWidget *parent)
		: QWidget(parent), _mouseLeftPress(false),_textEdit(false),_value(0.0f),
		_deltaValue(0.1f),_maxValue(FLT_MAX),_minValue(FLT_MIN)
	{
		_lineEdit=new QLineEdit(this);
		_label=new QLabel("",this);

		_layout=new QGridLayout(this);
		_layout->addWidget(_lineEdit,0,0);
		_layout->addWidget(_label,0,0);

		_lineEdit->hide();

		this->setLayout(_layout);
		this->setMaximumSize(QSize(64,32));
		this->setMinimumSize(QSize(64,32));

		connect(_lineEdit,SIGNAL(editFinished()),this,SLOT(OnTextFinished()));
	}

	NumericTextEdit::NumericTextEdit(float value,QWidget *parent)
		: QWidget(parent), _mouseLeftPress(false),_textEdit(false),_value(0.0f),
		_deltaValue(0.1f),_maxValue(FLT_MAX),_minValue(FLT_MIN)
	{
		
		_lineEdit=new QLineEdit(this);
		_label=new QLabel("",this);

		_layout=new QGridLayout(this);
		_layout->addWidget(_lineEdit,0,0);
		_layout->addWidget(_label,0,0);

		_lineEdit->hide();

		this->setLayout(_layout);
		this->setMaximumSize(QSize(64,32));
		this->setMinimumSize(QSize(64,32));

		this->setFloat(value);
		connect(_lineEdit,SIGNAL(editFinished()),this,SLOT(OnTextFinished()));
	}

	void NumericTextEdit::OnTextFinished()
	{
		QString txt=_lineEdit->text();
		bool ok=false;
		float value=txt.toFloat(&ok);
		if(ok){
			setFloat(value);
		}else{
			setFloat(_value);
		}
		textEditFinished();
	}

	void NumericTextEdit::setFloat(float value)
	{
		/*
		if(value>=_maxValue){
			value=_maxValue;
		}
		if(value<=_minValue){
			value=_minValue;
		}
		*/
		_value=value;

		_lineEdit->setText(QString().setNum(_value,'f',4));
		_label->setText(QString().setNum(_value,'f',4));
	}

	void NumericTextEdit::mousePressEvent(QMouseEvent *evt)
	{
		if(evt->button()==Qt::LeftButton){
			_mouseLeftPress=true;
			setCursor(QCursor(Qt::SizeHorCursor));
		}
	}

	void NumericTextEdit::mouseReleaseEvent(QMouseEvent *evt)
	{
		if(evt->button()==Qt::LeftButton){
			_mouseLeftPress=false;
			setCursor(QCursor(Qt::ArrowCursor));
		}
	}

	void NumericTextEdit::mouseDoubleClickEvent(QMouseEvent *evt)
	{
		_textEdit=true;
		_label->hide();
		_lineEdit->show();
	}

	void NumericTextEdit::mouseMoveEvent(QMouseEvent *evt)
	{
		if(_mouseLeftPress){
			if(evt->pos().x()>_mousePosition.x()){
				inc();	
			}else{
				dec();
			}
			
			_mousePosition=evt->pos();
		}
	}

	void NumericTextEdit::leaveEvent(QEvent *evt)
	{
		textEditFinished();
	}

	void NumericTextEdit::textEditFinished()
	{
		if(_textEdit){
			_label->show();
			_lineEdit->hide();
			_textEdit=false;
		}
	}
}
